package com.hz.ruoyiequipment.warning.service.impl;

import com.hz.ruoyiequipment.warning.domain.vo.AgrAlertLinkResultVo;
import com.hz.ruoyiequipment.warning.mapper.AgrAlertLinkMapper;
import com.ruoyi.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class ThresholdRedisService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private AgrAlertLinkMapper agrAlertLinkMapper;



    // Redis Key 前缀
    private static final String THRESHOLD_KEY_PREFIX = "agr_equipment:waring_sourceId:";

    // 初始化 Redis 数据
    @PostConstruct
    public void initRedisData() {
        // 1. 删除 Redis 中所有相关数据
        deleteAllThresholdRules();
        List<AgrAlertLinkResultVo> allRules = agrAlertLinkMapper.getAllBySourceId(null);
        for (AgrAlertLinkResultVo rule : allRules) {
            String key = THRESHOLD_KEY_PREFIX + rule.getSourceId();
            String ruleId = "rule:" + rule.getFieldId(); // 规则 ID
            redisService.setCacheMapValue(key, ruleId, rule);
        }
        log.info("阈值信息已加载到 Redis");
    }
    /**
     * 删除 Redis 中所有相关数据
     */
    private void deleteAllThresholdRules() {
        // 获取所有匹配 THRESHOLD_KEY_PREFIX 的键
        Set<String> keys = (Set<String>) redisService.keys(THRESHOLD_KEY_PREFIX + "*");

        if (keys != null && !keys.isEmpty()) {
            // 批量删除
            redisService.deleteObject(keys);
            log.info("已删除 {} 条旧阈值规则", keys.size());
        } else {
            log.info("未找到需要删除的旧阈值规则");
        }
    }

    // 从 Redis 获取阈值规则
    public Map<String, AgrAlertLinkResultVo> getThresholdRules(Long equipmentId) {
        String key = THRESHOLD_KEY_PREFIX + equipmentId;
        return redisService.getCacheMap(key);
    }

    // 更新 Redis 中的阈值规则
    public void updateThresholdRules(Long equipmentId, String ruleId, AgrAlertLinkResultVo rule) {
        String key = THRESHOLD_KEY_PREFIX + equipmentId;
        redisService.setCacheMapValue(key, ruleId, rule);
        log.info("Redis 中的阈值规则已更新，设备ID: {}, 规则ID: {}", equipmentId, ruleId);
    }

    // 删除 Redis 中的阈值规则
    public void deleteThresholdRules(Long equipmentId, String ruleId) {

        String key = THRESHOLD_KEY_PREFIX + equipmentId;
        if (equipmentId == null) {
            key= THRESHOLD_KEY_PREFIX+"*";
            ruleId="rule:*";
        }
        redisService.deleteCacheMapValue(key, ruleId);
        log.info("Redis 中的阈值规则已删除，设备ID: {}, 规则ID: {}", equipmentId, ruleId);
    }
}
